package com.shadowtorcher.dragonstreasure.controller;

import com.google.gson.Gson;
import com.shadowtorcher.dragonstreasure.config.Config;
import com.shadowtorcher.dragonstreasure.url.UploadURL;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadFileController {
    @RequestMapping(value = "/upload/{uuid}", method = RequestMethod.POST)
    public void doUpload(@RequestParam("data") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @PathVariable String uuid) throws IOException {

        Gson gson = new Gson();
        Map<String, String> ans = new HashMap<>();

        System.out.println("[INFO]get upload request");

        UploadURL uploadURL = new UploadURL();
        uploadURL.setUUID(uuid);
        String UA = request.getHeader("User-Agent");
        if (!UA.contains("dragons-treasure-client")) {
            response.setStatus(403);
            System.out.println("[INFO]URL 403");
            return;
        }

        File uploadDir = new File(Config.PATH);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        String fileName = uploadURL.getUUID();
        System.out.println("[INFO]fileName" + fileName);
        String filePath = Config.PATH + File.separator + fileName + ".data";
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
        bufferedOutputStream.write(file.getBytes());
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
        System.out.println("[INFO]write file" + fileName);
        ans.put("state", "success");
        gson.toJson(ans, response.getWriter());
    }
}
